package com.yjd.api.user;

import com.alibaba.fastjson.JSON;
import com.yjd.comm.bank.model.BankModel;
import com.yjd.comm.bank.service.IBankService;
import com.yjd.comm.base.control.BaseControl;
import com.yjd.comm.base.enums.DbWREnums;
import com.yjd.comm.credit.model.CreditLineApplyModel;
import com.yjd.comm.credit.service.ICreditLineApplyService;
import com.yjd.comm.enums.OrderStatusEnum;
import com.yjd.comm.enums.ReferenceTypeEnum;
import com.yjd.comm.enums.StagesStatusEnum;
import com.yjd.comm.fs.util.FileUtil;
import com.yjd.comm.order.model.OrderModel;
import com.yjd.comm.order.service.IOrderService;
import com.yjd.comm.repayment.model.RepaymentDataModel;
import com.yjd.comm.repayment.service.IRepaymentDataService;
import com.yjd.comm.resource.model.ResourceModel;
import com.yjd.comm.system.util.SysParamUtil;
import com.yjd.comm.user.dto.ContactInfo;
import com.yjd.comm.user.dto.MultiContact;
import com.yjd.comm.user.dto.ResidenceInfo;
import com.yjd.comm.user.model.UserDataModel;
import com.yjd.comm.user.model.UserModel;
import com.yjd.comm.user.dto.WorkInfo;
import com.yjd.comm.user.service.IUserDataService;
import com.yjd.comm.user.service.IUserService;
import com.yjd.comm.user.util.UserUtil;
import com.yjd.comm.util.*;
import com.yjd.comm.vo.Constant;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * 用户信息相关操作
 * Created by yangchangyan on 2017/6/28.
 */
@Controller("com.yjd.api.user.UserInfoControl")
@Scope("prototype")
@RequestMapping("/user/info")
public class UserInfoControl extends BaseControl {

    @Resource
    private IUserDataService userDataService;

    @Resource
    private IUserService userService;

    @Resource
    private IOrderService orderService;

    @Resource
    private IRepaymentDataService repaymentDataService;

    @Resource
    private ICreditLineApplyService creditLineApplyService;

    @Resource
    private IBankService bankService;

    /**
     * 用户信息
     * 可能包含不同的用户信息
     *
     * @param
     * @return void
     * @throws
     */
    @RequestMapping("")
    public void userInfo() throws Exception {
        Map<String, Object> paramMap = ServletUtil.getParameterMap(request);
        Long user_id = this.getUserSession().getUser_id();

        // 是否绑卡
        BankModel userBankInfo = bankService.getModelById(user_id, DbWREnums.READ);
        boolean isBindCard = UserUtil.isUserBindCardCompleted(userBankInfo);

        // 是否实名
        UserDataModel userData = userDataService.getModelById(user_id, DbWREnums.READ);
        boolean isRealName = UserUtil.isUserRealNameCompleted(userData);

        // 居住信息验证
        boolean isResidenceCompleted = false;

        // 工作情况验证
        boolean isJobInfoCompleted = false;

        // 紧急联系人验证
        boolean isUrgentContactCompleted = false;

        if(null != userData){
            if( StringUtil.isNotEmpty(userData.getResidence()) ){
                ResidenceInfo residenceInfo = JSON.parseObject(userData.getResidence(), ResidenceInfo.class);
                isResidenceCompleted = UserUtil.isResidenceInfoCompleted(residenceInfo);
            }

            if( StringUtil.isNotEmpty(userData.getJob_info()) ){
                WorkInfo workInfo = JSON.parseObject(userData.getJob_info(), WorkInfo.class);
                isJobInfoCompleted = UserUtil.isJobInfoCompleted(workInfo);
            }

            if( StringUtil.isNotEmpty(userData.getUrgent_contacts()) ){
                List<ContactInfo> contactInfos = JSON.parseArray(userData.getUrgent_contacts(), ContactInfo.class);
                isUrgentContactCompleted = UserUtil.isUrgentContactInfoCompleted(contactInfos);
            }
        }

        paramMap.put("isBindCard", isBindCard);
        paramMap.put("isRealName", isRealName);
        paramMap.put("isResidenceCompleted", isResidenceCompleted);
        paramMap.put("isJobInfoCompleted", isJobInfoCompleted);
        paramMap.put("isUrgentContactCompleted", isUrgentContactCompleted);

        this.successData(paramMap);
    }

    /**
     * 判断用户的工作信息，联系人信息是否完整
     * 0：不完整，1：部分完整，2：完整
     * Created by yangchangyan on 2017/10/15.
     *
     * @param
     * @return
     * @throws
     */
    @RequestMapping("/integrity/verify")
    public void userInfoIntegrityVerify() throws Exception {
        Map<String, Object> paramMap = ServletUtil.getParameterMap(request);
        // 默认信用额度
        String limit = SysParamUtil.getValue(Constant.SysParamKeyEnum.CREDIT_LIMIT_MIN);
        paramMap.put("defaultLimit", limit);

        // 资料完整度
        Long user_id = this.getUserSession().getUser_id();
        int integrity = userDataService.isUserInfoCompleted(user_id);
        paramMap.put("integrity", integrity);

        // 如果用户的资料完整，则自动通过默认额度的申请
        if(integrity == 2){
            UserDataModel userData = userDataService.getModelById(user_id, DbWREnums.WRITE);
            if(null != userData && userData.getCredit_line() <= 0){
                CreditLineApplyModel apply = creditLineApplyService.getModelOne(
                        FrameUtil.newHashMap("user_id", user_id, "status", OrderStatusEnum.INIT.getCode(), "apply_credit_line", limit), DbWREnums.WRITE);
                if(null != apply){
                    // 1通过 2拒绝
                    creditLineApplyService.apply(apply.getId(), 1);
                }
            }
        }

        this.successData(paramMap);
    }

    @RequestMapping("/job")
    public void jobInfo() throws Exception {
        Map<String, Object> paramMap = ServletUtil.getParameterMap(request);
        WorkInfo workInfo = JSON.parseObject(queryUserData().getJob_info(), WorkInfo.class);
        if (null == workInfo) {
            workInfo = new WorkInfo();
        }
        paramMap.put("jobInfo", workInfo);
        this.successData(paramMap);
    }

    /**
     * 更新工作信息
     *
     * @param jobInfo JSON格式的工作信息，可多条
     * @param
     * @return void
     * @throws
     */
    @RequestMapping("/job/update")
    public void updateJobInfo(WorkInfo jobInfo) throws Exception {
        if (null == jobInfo) {
            FrameUtil.throwBaseException1("工作信息不能为空");
        }
        userDataService.updateByMap(this.getUserSession().getUser_id(),
                FrameUtil.newHashMap("job_info", JSON.toJSONString(jobInfo)));
        this.successMsg("更新工作信息成功");
    }

    @RequestMapping("/contact")
    public void contactInfo() throws Exception {
        Map<String, Object> paramMap = ServletUtil.getParameterMap(request);
        ContactInfo contactInfo = JSON.parseObject(queryUserData().getContacts(), ContactInfo.class);
        if (null == contactInfo) {
            contactInfo = new ContactInfo();
        }
        String mobile_number = StringUtil.isEmpty(contactInfo.getMobile_number()) ? "" : UserUtil.disposeMobile(contactInfo.getMobile_number());
        contactInfo.setMobile_number(mobile_number);
        paramMap.put("contactInfo", contactInfo);
        this.successData(paramMap);
    }

    /**
     * 更新工作信息
     *
     * @param contacts JSON格式的联系人信息，可多条
     * @param
     * @return void
     * @throws
     */
    @RequestMapping("/contact/update")
    public void updateContactInfo(ContactInfo contacts) throws Exception {
        if (null == contacts) {
            FrameUtil.throwBaseException1("联系人信息不能为空");
        }
        userDataService.updateByMap(this.getUserSession().getUser_id(),
                FrameUtil.newHashMap("contacts", JSON.toJSONString(contacts)));
        this.successMsg("更新联系人信息成功");
    }

    @RequestMapping("/residence")
    public void residenceInfo() throws Exception {
        Map<String, Object> paramMap = ServletUtil.getParameterMap(request);
        ResidenceInfo residenceInfo = JSON.parseObject(queryUserData().getResidence(), ResidenceInfo.class);
        if (null == residenceInfo) {
            residenceInfo = new ResidenceInfo();
        }
        paramMap.put("residenceInfo", residenceInfo);
        this.successData(paramMap);
    }

    /**
     * 居住信息
     *
     * @param residence JSON格式的居住信息，可多条
     * @param
     * @return void
     * @throws
     */
    @RequestMapping("/residence/update")
    public void updateResidenceInfo(ResidenceInfo residence) throws Exception {
        if (null == residence) {
            FrameUtil.throwBaseException1("地址信息不能为空");
        }

        userDataService.updateByMap(this.getUserSession().getUser_id(),
                FrameUtil.newHashMap("residence", JSON.toJSONString(residence)));

        this.successMsg("更新地址信息成功");
    }

    @RequestMapping("/contact/urgent")
    public void urgentContactInfo() throws Exception {
        Map<String, Object> paramMap = ServletUtil.getParameterMap(request);
        List<ContactInfo> contactInfos = JSON.parseArray(queryUserData().getUrgent_contacts(), ContactInfo.class);
        if (null == contactInfos) {
            contactInfos = Collections.emptyList();
        }
        for(ContactInfo ci : contactInfos){
            String mobile_number = StringUtil.isEmpty(ci.getMobile_number()) ? "" : UserUtil.disposeMobile(ci.getMobile_number());
            ci.setMobile_number(mobile_number);
        }
        paramMap.put("contactInfo", contactInfos);
        this.successData(paramMap);
    }

    /**
     * 更新工作信息
     *
     * @param contacts JSON格式的联系人信息，可多条
     * @param
     * @return void
     * @throws
     */
    @RequestMapping("/contact/urgent/update")
    public void updateUrgentContactInfo(MultiContact contacts) throws Exception {
        if (null == contacts || null == contacts.getContacts()) {
            FrameUtil.throwBaseException1("联系人信息不能为空");
        }
        userDataService.updateByMap(this.getUserSession().getUser_id(),
                FrameUtil.newHashMap("urgent_contacts", JSON.toJSONString(contacts.getContacts())));
        this.successMsg("更新联系人信息成功");
    }

    private UserDataModel queryUserData() throws Exception {
        Long user_id = this.getUserSession().getUser_id();
        UserDataModel userData = userDataService.getModelById(user_id, DbWREnums.READ);
        if (null == userData) {
            FrameUtil.throwBaseException1("查询失败，稍后重试。");
        }

        return userData;
    }

    @RequestMapping("/img/upload")
    public void upload(MultipartHttpServletRequest request) throws Exception {

        Long user_id = super.getSessionUserId();

        ResourceModel res = new ResourceModel();
        res.setRef_type(ReferenceTypeEnum.PORTRAIT.getCode());
        res.setRef_id(user_id);
        String portrait_path = FileUtil.uploadFileToRemote(request.getFileMap(), ReferenceTypeEnum.PORTRAIT, res);
        // 更新用户头像
        UserModel userModel = new UserModel();
        userModel.setUser_id(user_id);
        userModel.setPortrait_path(portrait_path);
        int count = userService.update(userModel);

        if (count == 0) {
            this.errorMsg(null, "文件上传失败");
        } else {
            this.successMsg("文件上传成功！");
        }
    }

    @RequestMapping("/protocol")
    public String agreement() throws Exception {
        return "user/protocolTemplate";
    }

    @RequestMapping("/borrow/protocol")
    public String borrowProtocol(Long order_id) throws Exception {
        OrderModel orderModel = orderService.getModelById(order_id, DbWREnums.READ);
        if(orderModel==null){
            FrameUtil.throwBaseException1("您查看的订单不存在!");
        }
        Long user_id = this.getUserSession().getUser_id();
        if(user_id.intValue()!=orderModel.getUser_id().intValue()){
            FrameUtil.throwBaseException1("当前订单不属于您的！");
        }

        if(StagesStatusEnum.REPAYMENTING.getCode()==orderModel.getStatus().intValue()
               || StagesStatusEnum.MERCHANT_CONFIRM_CANCEL.getCode()==orderModel.getStatus().intValue() ||
                StagesStatusEnum.REPAYMENED.getCode()==orderModel.getStatus().intValue()){
            UserDataModel userData = userDataService.getModelById(orderModel.getUser_id(), DbWREnums.READ);
            RepaymentDataModel repaymentDataModel = repaymentDataService.getModelOne(FrameUtil.newHashMap("order_id", orderModel.getOrder_id(), "period", 1), DbWREnums.READ);
            if(repaymentDataModel==null){
                FrameUtil.throwBaseException1("您的借款协议不存在");
            }
            request.setAttribute("protoclNo","MFQJK"+orderModel.getOrder_no());
            request.setAttribute("idName",userData.getId_name());
            request.setAttribute("loan_amout", NumberUtil.formatNumber(orderModel.getLoan_amount(), NumberUtil.FORMAT_4));
            request.setAttribute("loan_limit",orderModel.getPeriod());
            request.setAttribute("fee_limit",NumberUtil.formatNumber( ArithUtil.div(ArithUtil.div(ArithUtil.mul(orderModel.getLoan_amount(),3), 100),
                    orderModel.getPeriod().doubleValue()), NumberUtil.FORMAT_4));
            Long start_date = repaymentDataModel.getEstimation_repayment_time();
            Long end_date = DateUtil.getLastSecond(DateUtil.addMonth(start_date, orderModel.getPeriod()));
            request.setAttribute("loan_start_date", DateUtil.timestampToDateString(start_date, DateUtil.PATTERN_yyyy_MM_dd));
            request.setAttribute("loan_end_date", DateUtil.timestampToDateString(end_date, DateUtil.PATTERN_yyyy_MM_dd));
            request.setAttribute("month_amount", NumberUtil.formatNumber(repaymentDataModel.getRepayment_amount(), NumberUtil.FORMAT_4));
            return "user/borrowProtocol";
        }else{
            FrameUtil.throwBaseException1("当前订单暂无借款协议！");
        }
        return null;


    }
}
